package de.reminder.server;

import java.util.logging.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.reminder.client.service.FacebookGraphAPIService;
import de.reminder.shared.model.FacebookUser;
import de.reminder.shared.model.json.GetFriendsResponse;

import com.google.gson.Gson;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class FacebookServlet extends RemoteServiceServlet implements FacebookGraphAPIService {
	
    private static final Logger log = Logger.getLogger(FacebookServlet.class.getName());


	private String getURLContent(String urlString, String accessToken) throws Exception{
		String result = "";
		String resultURL = urlString+"?access_token="+URLEncoder.encode(accessToken);
		URL url = new URL(resultURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		int responseCode = connection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				result += line;
			}
			reader.close();
			return result;
		} else {
			throw new Exception("Wrong response code:"+responseCode);
		}
	}

	@Override
	public List<FacebookUser> getFriends(FacebookUser user, String accessToken)
			throws Exception {
		log.info("Get friends of User: "+user);
		String content = getURLContent("https://graph.facebook.com/"+user.getId()+"/friends",accessToken);
        Gson gson = new Gson();
        return (gson.fromJson(content, GetFriendsResponse.class)).data;
	}
}
